package com.fuyin.commons.utils;

import com.fuyin.commons.exception.Asserts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description
 * @date 2021年10月29日 11:58 上午
 * @since
 */
@Slf4j
@Component
public class MyUtils {

    private MyUtils() {
    }

    /**
     * 转化总分值
     *
     * @param zfz 可能是一个整数，表示=，可能是'15-18'格式，可能是'>0'格式，可能是'<2'格式
     * @return {@link List<Double>}
     * @author 袁希岚
     * @date 2021/11/13 <br>
     * @since
     */
    public static List<Double> getZfz(String zfz) {
        if (StringUtils.isBlank(zfz)) {
            return Arrays.asList(1.0, 0.0);
        }
        List<Double> zfzs = new ArrayList<>();
        try {
            if (zfz.contains("-")) {
                String[] values = zfz.split("-");
                zfzs.add(Double.parseDouble(values[0]));
                zfzs.add(Double.parseDouble(values[1]));
            } else if (zfz.contains(">")) {
                zfzs.add(Double.parseDouble(zfz.substring(1)));
                zfzs.add(Double.MAX_VALUE);
            } else if (zfz.contains("<")) {
                zfzs.add(Double.MIN_VALUE);
                zfzs.add(Double.parseDouble(zfz.substring(1)));
            } else {
                double value = Double.parseDouble(zfz);
                zfzs.add(value);
                zfzs.add(value);
            }
        } catch (Exception e) {
            log.error("com.fuyin.commons.utils.MyUtils#getZfz, zfz: {}", zfz);
            return new ArrayList<>();
        }
        return zfzs;
    }

    /**
     * 转化评分标准值
     *
     * @param bzz 可能是一个具体的值，那么会取上下区间 10%，也可能是 '30%-60%' 格式，进行拆分
     * @return {@link List<Integer>}
     * @author 袁希岚
     * @date 2021/11/12 <br>
     * @since
     */
    public static List<Double> getBzz(String bzz) {
        if (StringUtils.isBlank(bzz)) {
            return Arrays.asList(1.0, 0.0);
        }
        List<Double> bzzs = new ArrayList<>();
        try {
            if (bzz.contains("-")) {
                String[] values = bzz.split("-");
                for (int i = 0; i < 2; ++i) {
                    if (values[i].contains("%")) {
                        values[i] = values[i].substring(0, values[i].length() - 1);
                        double value = Double.parseDouble(values[i]);
                        value /= 100.0;
                        bzzs.add(value);
                    } else {
                        bzzs.add(Double.parseDouble(values[i]));
                    }
                }
            } else if (bzz.contains(">")) {
                bzzs.add(Double.parseDouble(bzz.substring(1)));
                bzzs.add(Double.MAX_VALUE);
            } else if (bzz.contains("<")) {
                bzzs.add(Double.MIN_VALUE);
                bzzs.add(Double.parseDouble(bzz.substring(1)));
            } else {
                if (bzz.contains("%")) {
                    bzz = bzz.substring(0, bzz.length() - 1);
                    double value = Double.parseDouble(bzz);
                    value /= 100.0;
                    bzzs.add(value - value * 0.1);
                    bzzs.add(value + value * 0.1);
                } else {
                    double value = Double.parseDouble(bzz);
                    bzzs.add(value - value * 0.1);
                    bzzs.add(value + value * 0.1);
                }
            }
        } catch (Exception e) {
            log.error("com.fuyin.commons.utils.MyUtils.getBzz e:{}", e.getMessage());
            return bzzs;
        }
        return bzzs;
    }

    public static void checkParams(String errorMessage, Object... params) {
        for (Object param : params) {
            if (param instanceof String) {
                if (StringUtils.isBlank((String) param)) {
                    Asserts.fail(errorMessage);
                }
            } else {
                if (Objects.isNull(param)) {
                    Asserts.fail(errorMessage);
                }
            }
        }
    }

    public static Date parseDayDate(String date) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        return formatter.parse(date);
    }

    /**
     * 将 Java 对象序列化为 byte []
     *
     * @param obj
     * @return {@link byte[]}
     * @author 袁希岚
     * @date 2021/11/24 <br>
     * @since
     */
    public static byte[] objToByte(Object obj) throws Exception {
        byte[] ret = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(obj);
        out.close();
        ret = baos.toByteArray();
        baos.close();
        return ret;
    }

    /**
     * 将 byte [] 反序列化为 Java 对象
     *
     * @param bytes
     * @return {@link Object}
     * @author 袁希岚
     * @date 2021/11/24 <br>
     * @since
     */
    public static Object byteToObj(byte[] bytes) throws Exception {
        Object ret = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(bais);
        ret = in.readObject();
        in.close();
        return ret;
    }

    //
//    public static User getUserByToken(String token) {
//        if (StringUtils.isBlank(token)) {
//            log.error("com.fuyin.commons.utils.MyUtils.getUserByToken token is null");
//            return new User();
//        }
//        token = StringUtils.substring(token, tokenHead.length());
//        String userName =jwtTokenUtil.getUserNameFromToken(token);
//        if (StringUtils.isBlank(userName)) {
//            log.error("com.fuyin.commons.utils.MyUtils.getUserByToken userName is null");
//            return new User();
//        }
//        User user = userDao.getUserByUserName(userName);
//        if (Objects.isNull(user)) {
//            log.error("com.fuyin.commons.utils.MyUtils.getUserByToken user is null");
//            return new User();
//        }
//        return user;
//    }

    public static String getIpAddr(HttpServletRequest request) {
        log.info("request request_url: {}, ip_address, {}", request.getRequestURL(), request.getHeader("ip_address"));
        if (StringUtils.isNotBlank(request.getHeader("ip_address"))) {
            return request.getHeader("ip_address");
        }
        log.error("request no ip_address, {}", request.getRequestURL());
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            String localIp = "127.0.0.1";
            String localIpv6 = "0:0:0:0:0:0:0:1";
            if (ipAddress.equals(localIp) || ipAddress.equals(localIpv6)) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        String ipSeparate = ",";
        int ipLength = 15;
        if (ipAddress != null && ipAddress.length() > ipLength) {
            if (ipAddress.indexOf(ipSeparate) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(ipSeparate));
            }
        }
        return ipAddress;
    }

//    public static boolean judgeVerification(HttpServletRequest request, String code) {
//        log.info("judgeVerification session:{}", request.getSession().getId());
//        if (StringUtils.isBlank(code)) {
//            log.error("com.fuyin.commons.utils.MyUtils#judgeVerification code is null");
//            return false;
//        }
//        if (Objects.isNull(request.getSession())) {
//            log.error("session is null");
//            return false;
//        }
//        log.info("request.getSession().getAttribute(CAPTCHA_KEY): {}", request.getSession().getAttribute("CAPTCHA_KEY"));
//        return code.equalsIgnoreCase((String) request.getSession().getAttribute("CAPTCHA_KEY"));
//    }

    public static File transferToFile(MultipartFile multipartFile) {
        // 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (Exception e) {
            log.info("com.fuyin.commons.utils.MyUtils.transferToFile e: {}", e);
        }
        return file;
    }
}
